<?php

namespace addons\hlapp\controller;

use addons\hlapp\dto\Result;
use addons\hlapp\dto\WXResult;
use addons\hlapp\model\HlappEvaluateSendLogs;
use addons\hlapp\model\HlappMember;
use addons\hlapp\model\HlappPart;
use addons\hlapp\model\HlappProject;
use addons\hlapp\model\HlappProjectEvaluate;
use addons\hlapp\model\HlappProjectRolesMember;
use addons\hlapp\model\HlappProjectSolve;
use addons\hlapp\model\HlappProjectStatus;
use addons\hlapp\model\HlappWrongSendLogs;
use addons\hlapp\service\PushService;
use think\Db;
use think\Exception;
use think\Log;

class Open extends Common
{
    public function test()
    {
        $time = time();
        echo $time;
        echo "<br>";
        echo $time-24*60*60;
    }

    // ----- 定时任务 --------------------------------

    /**
     * 项目超期1天内的推送总经理
     */
    public function pushOverdue()
    {
        $projects = HlappProject::where('status', 1)
            ->where('end_time', '<', time())
            ->where('end_time', '>', time() - 3600)
            ->select();
        foreach ($projects as $project) {
            $member = HlappMember::get($project['topmanager_id']);
            $this->sendWrongToMember($project['id'], "项目超期警告！", "");
        }
    }

    /**
     * 超过 24小时未评价 甲方自动 满意 评价
     * 定时任务
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function taskEvaluateOk()
    {
        $e = new HlappProjectEvaluate();
        $evaluates = $e->where('status', null)
            ->where('create_time','<',time()-24*60*60)
            ->select();
        foreach ($evaluates as $item) {
            $evaluate['id'] = $item['id'];
            $evaluate['status'] = 1;
            $evaluate['isauto']=1;
            $evaluate['evaluateInfo'] = '[{"key":"施工进度及材料进场方面","value":"满意"},{"key":"施工质量方面及各工序隐蔽验收情况","value":"满意"},{"key":"现场项目部及劳务班组配合度方面","value":"满意"},{"key":"现场安全文明方面","value":"满意"}]';
            (new HlappProjectEvaluate())->saveOrUpdata($evaluate);
        }
    }

    /**
     * 重置本周推送状态
     * => '未评价'
     * =>'未推送'
     */
    public function taskNoevaluate(){
        //如果今天是周一
        if (!(date('w') - 1)){
            \Log::INFO("重置本周推送状态");
            Db::table('hl_hlapp_project')->where('isPush', 1)->update(['isPush'=>0]);
            Db::table('hl_hlapp_project')->where('isEvaluated', 1)->update(['isEvaluated'=>0]);
        }
    }

//    /**
//     * 一天内未给出评价方案的，再次推送解决方案消息模板
//     */
//    public function PushNoSolveAtDay()
//    {
//        $e = new HlappProjectEvaluate();
//
//        //将评价信息推送项目负责人
//        $project = HlappProject::getProject($projectId);
//        if ($project['manager_id']) {
//            $this->sendSolveToMember($projectId, $project['manager_id'], $week, $id, "manager");
//        }
//        if ($project['engineer_id']) {
//            $this->sendSolveToMember($projectId, $project['engineer_id'], $week, $id, "engineer");
//        }
//        if ($project['collection_id']) {
//            $this->sendSolveToMember($projectId, $project['collection_id'], $week, $id, "collection");
//        }
//        if ($project['operate_id']) {
//            $this->sendSolveToMember($projectId, $project['operate_id'], $week, $id, "operate");
//        }
//        if ($project['engineering_id']) {
//            $this->sendSolveToMember($projectId, $project['engineering_id'], $week, $id, "engineering");
//        }
//
//}


    // -------------------- 定时任务结束 --------------------------
    /**
     * 已经改成手动发送
     * 给 甲方 发送评价信息
     * 定时任务接口
     * 对进行中，有甲方项目总负责人，开始周数大于0的项目发送评价信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
//    public  function taskSendEvaluate(){
//        $projects = (new HlappProject())->where('status',1)->select();
//        foreach ($projects as $project){
//            if ($project['amamager_id']){
//                $member=HlappMember::get($project['amamager_id']);
//                $week = $this->getWeeks($project->getData('start_time'),time());
//                if($week > 0){
//                    $e = new HlappProjectEvaluate();
//                    $evaluate['projectId']=$project['id'];
//                    $evaluate['stage']=$project->getData('stage');
//                    $evaluate['week']=$week;
//                    $eid=$e->saveOrUpdata($evaluate);
//                    if ($eid){
//                        $this->sendEvaluateToMember($project['id'],$member['openId'],$week,$eid);
//                    }
//                }
//            }
//        }
//    }

    /**
     *  1天内未评价的再次推送评价信息
     */
//    public function SendNoEvaluateOneDay(){
//        $e =  new HlappProjectEvaluate();
//        $evaluates = $e->noEvaluate(24);
//        foreach ($evaluates as $evaluate){
//            $project = HlappProject::get($evaluate['projectId']);
//            $member=HlappMember::get($project['amamager_id']);
//            $week = $this->getWeeks($project->getData('start_time'),time());
//            $this->sendEvaluateToMember($project['id'],$member['openId'],$week,$evaluate['id']);
//        }
//    }



    /**
     *  推送三次以上不满意的项目
     */
    public function pushTwiceBadEvaluate($projectId){
        $this->sendWrongToMember($projectId,"甲方评价连续三次及以上不满意！","");
    }

    /**
     * 发送项目警告消息
     */
    public function sendWrongToMember($projectId,$wrongTitle,$remark){
        $projectModel = new HlappProject();
        $project = $projectModel->where("id",$projectId)->find();
        $topManagers = (new HlappMember())->where('partId',HlappPart::$TOPMANAGER)->select();

        $log['projectId']=$projectId;
        $log['stage']=$project['stage'];
        $log['member']=$project['amamager']['name'];
        $log['status'] = 0;
        if ($topManagers){
            foreach ($topManagers as $item){
                $openId = $item['openId'];
                $templateId="sZiuzUkyrCCcVHuKr3TWEBt1nHHdxoTwGwZ1SJXcgH0";
                $jumpUrl="";
                $data=[
                    "first"=>["value"=>$wrongTitle,"color"=>"#DC2C26"],
                    "keyword1"=>["value"=>$project["name"],"color"=>"#173177"],
                    "keyword2"=>["value"=>$project['amamager']['name'],"color"=>"#173177"],
                    "keyword3"=>["value"=>$project['stage'],"color"=>"#173177"],
                    "remark"=>["value"=>$remark,"color"=>"#173177"]
                ];
                if($openId){
                    $r = (new PushService())->sendTemplateMessage($openId,$templateId,$jumpUrl,$data);
                    if($r->code){
                        $log['status'] = 1;
                    }else{
                        if ($r->message){
                            $log['message'] = $r->message;
                        }else{
                            $log['message'] = "警告信息发送失败";
                        }
                    }
                }else {
                    $log['message'] = "请负责人先进行信息登记！";
                }
                (new HlappWrongSendLogs())->saveOrUpdata($log);
            }
        }else{
            Log::ERROR("没有录入总经理信息！");
        }
    }

    /**
     * 给甲方发送评价消息
     * @param $projectId 项目id
     * @param $openId 用户openId
     * @param $week 周数
     * @param $eid 评价id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function sendEvaluateToMember($projectId,$openId,$week,$eid){
        $res = Result::getResultError();
        \Log::INFO("给甲方发送评价信息！");
        $projectModel = new HlappProject();
        $project = $projectModel->where("id",$projectId)->find();
        $templateId="sZiuzUkyrCCcVHuKr3TWEBt1nHHdxoTwGwZ1SJXcgH0";
        $jumpUrl=addonUrl("hlapp/Wap/evaluate",'',true,true);
        $jumpUrl = $jumpUrl."?eid=".$eid;
        \Log::INFO("the jumpUrl is:".$jumpUrl);
        $data=[
            "first"=>["value"=>$project["name"]."进度评价","color"=>"#173177"],
            "keyword1"=>["value"=>$project["name"],"color"=>"#173177"],
            "keyword2"=>["value"=>$project['amamager']['name'],"color"=>"#173177"],
            "keyword3"=>["value"=>$project['stage']."  第".$week."周","color"=>"#173177"],
            "remark"=>["value"=>"点击对编号".$eid."进度进行评价","color"=>"#173177"]
        ];
        $log['eId']=$eid;
        $log['projectId']=$projectId;
        $log['week']=$week;
        $log['stage']=$project['stage'];
        $log['member']=$project['amamager']['id'];
        $log['part']="amamager_id";
        $log['status'] = 0;
        $log['type']=1;
        if(!$openId){
            $log['message']= "请负责人先进行信息登记！";
            $res->setMessage("请负责人先进行信息登记！");
        }else{
            // 更新项目推送状态
            $response = (new PushService())->sendTemplateMessage($openId,$templateId,$jumpUrl,$data);
            if ($response->code){
                \Log::INFO("更新项目推送状态");
                $res = Result::getResultOk();
                $pro = HlappProject::get($projectId);
                $pro->isPush = 1;
                $pro->save();
                $log['status'] = 1;
            }else{
                $res->setResult($response);
            }
            $log['message'] = $response->message;
        }
        (new HlappEvaluateSendLogs)->saveOrUpdata($log);
        return $res;
    }

    /**
     * 模板消息重推
     */
    public function repush(){
        $eId = $_GET['eid'];
        $type = $_GET['type'];
        //如果是评价
        if ($type==1){
            $evaluate = (new HlappProjectEvaluate())->with('project')->find($eId);
            $project = HlappProject::getProject($evaluate->project->id);
            $this->sendEvaluateToMember($evaluate['projectId'],$project->amanager->openId,$evaluate['week'],$eId);

        }
    }

    /**
     *  项目开始
     *  获取项目未开始 但是 甲方已经关注的项目
     * 开始项目
     */
    public function getNoRegist()
    {
        $sql = "SELECT 
                            p.id,p.NAME,p.`status`,m.openId 
                            FROM hl_hlapp_project p 
                            LEFT JOIN hl_hlapp_member m ON m.id = p.amamager_id
                            WHERE m.openId IS not NULL AND p.`status` = 0 
                            AND m.delete_time IS NULL AND p.delete_time IS null";
        $projects = Db::query($sql);
        $info = "";
        foreach ($projects as $project) {
            $id = $project['id'];
            (new Project())->startProjectB($id);
            $info = $info ."id 为".$project['id']." 项目自动开始 \n";
        }
        \Log::INFO($info);
        return $info;
    }

    /**
     * 定时任务
     * 甲方评价不满意，且24小时内未上传解决措施的
     */
    public function noSolveProject(){
        $time = time() - (24 * 3600);
        $week = $this->getWeekOfYear(time());
        $evaluates = (new HlappProjectEvaluate())->where("week",$week)
            ->where("status",0)
            ->where('evaluate_time','<',$time)
            ->select();
        foreach ($evaluates as $evaluate){
            $solve = (new HlappProjectSolve())->where("eId",$evaluate['id'])->select();
            if ($solve && count($solve) < 1){
                (new PushService())->sendWrongEngineer($evaluate['id']);
            }
        }
    }
}